//
//  OtherInfoVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/29.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "OtherInfoVC.h"
#import "DynamicCell.h"
#import "MyVM.h"
#import "MJRefresh.h"
#import "PlanVM.h"
#import "TransactionRecordsCell.h"
#import "JoinQuizDetailVC.h"
#import "VisitRecordCell.h"
#import "PlanPeopleVC.h"
@interface OtherInfoVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic ,strong) UIImageView   *topImageV;
@property (nonatomic ,strong) UITableView   *tableView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) NSMutableArray *getFArr;
@property (nonatomic ,assign)NSInteger   page;


@end

@implementation OtherInfoVC{
    UIView *headView;
    NSInteger   selectType;
    UserInfoModel *model;
    BOOL      tableChange;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)setUserId:(NSString *)userId{
    _userId=userId;
    WS(weakSelf);
    [[MyVM manage] getUserInfoWithUserId:userId WithSuccess:^(id returnValue) {
        model=returnValue;
        [weakSelf headView];
        [weakSelf.tableView.header beginRefreshing];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 点击顶部分类
- (void)onclickType:(UITapGestureRecognizer *)tap{
    selectType=tap.view.tag;
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
    [self.tableView.header beginRefreshing];
}

- (void)getData{
    if (selectType==0) {
        [self getPlanList];
    }else if (selectType==1){
        [self getDynamicList];
    }else if (selectType==2){
        [self getVisitRecordList];
    }
}

#pragma mark -- 获取计划列表
- (void)getPlanList{
    WS(weakSelf);
    [[PlanVM manage] getMyPlanWithUid:self.userId andLtype:0 andWinState:0 andPageIndex:self.page Success:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.tableView.header endRefreshing];
        if (weakSelf.page==1) {
            [weakSelf.dataArr removeAllObjects];
        }
        weakSelf.page+=1;
        [weakSelf.dataArr addObjectsFromArray:returnValue];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.header endRefreshing];
    }];
}

#pragma mark -- 动态列表
- (void)getDynamicList{
    WS(weakSelf);
    [[MyVM manage] getDenamicWithUid:self.userId andPage:self.page andSuccess:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.tableView.header endRefreshing];
        weakSelf.page+=1;
        [weakSelf.dataArr addObjectsFromArray:returnValue];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.header endRefreshing];
    }];
}

#pragma mark -- 访客列表
- (void)getVisitRecordList{
    WS(weakSelf);
    [[MyVM manage] getVisitRecordWithUid:self.userId andPage:self.page andSuccess:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.tableView.header endRefreshing];
        if (weakSelf.page==1) {
            [weakSelf.getFArr removeAllObjects];
        }
        weakSelf.page+=1;
        [weakSelf.getFArr addObjectsFromArray:returnValue];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.header endRefreshing];
    }];;
}

#pragma mark --  编辑计划
- (void)editPlan:(PlanModel *)model{
    JoinQuizDetailVC *vc=[[JoinQuizDetailVC alloc]init];
    vc.title=model.LTypeName;
    vc.lType=model.lType;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark --关注
- (void)onclickFocus:(UIButton *)sender{
    sender.userInteractionEnabled=NO;
    if (model.isFollow) {
        [[MyVM manage] cancleFollowWithId:self.userId Success:^(id returnValue) {
            model.isFollow=NO;
            [sender setTitle:@"关注" forState:UIControlStateNormal];
            sender.userInteractionEnabled=YES;
        } andFail:^(NSString *errorMessage, NSError *error) {
            sender.userInteractionEnabled=YES;
        }];
    }else{
        [[MyVM manage] addFollowWithId:self.userId Success:^(id returnValue) {
            model.isFollow=YES;
            [sender setTitle:@"取消" forState:UIControlStateNormal];
            sender.userInteractionEnabled=YES;
        } andFail:^(NSString *errorMessage, NSError *error) {
            sender.userInteractionEnabled=YES;
        }];
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.hidden=YES;
    [self.navigationController.navigationBar setBackgroundImage:[TGTools createImageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    [self.navigationController.navigationBar setBackgroundImage:[TGTools createImageWithColor:NAVCOLOR] forBarMetrics:UIBarMetricsDefault];
}

- (void)tap:(UITapGestureRecognizer *)tap{
    //MARK:关注遇粉丝
}


#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (selectType==0) {
        return self.dataArr.count;
    }
    return self.getFArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 5, SCREEN_WIDTH, 44)];
    view.backgroundColor=[UIColor whiteColor];
    QXLable *labPlan=[self titleLab:@"计划"];
    labPlan.tag=0;
    [view addSubview:labPlan];
    [labPlan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(view);
        make.width.mas_equalTo(@(SCREEN_WIDTH/2.0));
    }];
    QXLable *labVisitors=[self titleLab:@"访客"];
    labVisitors.tag=2;
    [view addSubview:labVisitors];
    [labVisitors mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(view);
        make.width.mas_equalTo(@(SCREEN_WIDTH/2.0));
    }];
    
    UIView *lineView=[[UIView alloc]init];
    lineView.backgroundColor=NAVCOLOR;
    [view addSubview:lineView];
    float x=0;
    if (selectType>0) {
        x=SCREEN_WIDTH/2.0;
    }
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(view).with.offset(-5);
        make.centerX.equalTo(labPlan).with.offset(x);
        make.size.mas_equalTo(CGSizeMake(44, 2));
    }];
    
    UIView *topLine=[[UIView alloc]init];
    topLine.backgroundColor=DEFAULTBGCOLOR;
    [view addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(view);
        make.height.mas_equalTo(@5);
    }];
    
    UIView *bottomLine=[[UIView alloc]init];
    bottomLine.backgroundColor=DEFAULTBGCOLOR;
    [view addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(view);
        make.height.mas_equalTo(@5);
    }];
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    if (selectType==0) {
        TransactionRecordsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TransactionRecordsCell" forIndexPath:indexPath];
        cell.userId=self.userId;
        cell.planModel=self.dataArr[indexPath.row];
    
        WS(weakSelf);
        cell.editBlock = ^(PlanModel *model) {
            [weakSelf editPlan:model];
        };
        return cell;
    }else if (selectType==1){
        DynamicCell *cell=[tableView dequeueReusableCellWithIdentifier:@"DynamicCell" forIndexPath:indexPath];
        cell.model=self.dataArr[indexPath.row];
        return cell;
    }
    VisitRecordCell *cell=[tableView dequeueReusableCellWithIdentifier:@"VisitRecordCell" forIndexPath:indexPath];
    cell.model=self.getFArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (![[UserModel userModel].UserId isEqualToString:self.userId]) {
        if (selectType==0) {
            PlanModel *planModel=self.dataArr[indexPath.row];
            ExpertsModel *eModel=[[ExpertsModel alloc]init];
            eModel.UserId=self.userId;
            eModel.Avater=model.Avater;
            eModel.lType=[NSString stringWithFormat:@"%ld",planModel.lType];
            PlanPeopleVC *vc=[[PlanPeopleVC alloc]init];
            LotteryTypeModel *lotteryModel=[[LotteryTypeModel alloc]init];
            lotteryModel.lType=eModel.lType;
            lotteryModel.Name=planModel.LTypeName;
            vc.lotteryModel=lotteryModel;
            vc.model=eModel;
            vc.title=[NSString stringWithFormat:@"%@近期竞彩",planModel.LTypeName];
            vc.playName=planModel.PlayName;
//            [vc getPlayArr:eModel.lType];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (QXLable *)titleLab:(NSString *)title{
    QXLable *labPlan=[[QXLable alloc]initCenterTextWithText:title];
    labPlan.userInteractionEnabled=YES;
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onclickType:)];
    [labPlan addGestureRecognizer:tap];
    return labPlan;
}

#pragma mark -- 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        _tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page=1;
            [weakSelf.dataArr removeAllObjects];
            [weakSelf.getFArr removeAllObjects];
            [weakSelf.tableView reloadData];
            [weakSelf getData];
        }];
        _tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf getData];
        }];
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight=200;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TransactionRecordsCell class] forCellReuseIdentifier:@"TransactionRecordsCell"];
        [_tableView registerClass:[VisitRecordCell class] forCellReuseIdentifier:@"VisitRecordCell"];
        [_tableView registerClass:[DynamicCell class] forCellReuseIdentifier:@"DynamicCell"];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(headView.mas_bottom);
        }];
    }
    return _tableView;
}

- (UIImageView *)topImageV{
    if (!_topImageV) {
        float iphoneX=0;
        if (KIsiPhoneX) {
            iphoneX=20;
        }
        
        _topImageV=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, real_size(178+iphoneX))];
        _topImageV.userInteractionEnabled=YES;
        UIView *bgView=[[UIView alloc]init];
        bgView.backgroundColor=[UIColor colorWithWhite:0.0 alpha:.3];
        [_topImageV addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(_topImageV);
        }];
        
        
        UIImageView *headImage=[[UIImageView alloc]init];
        headImage.layer.masksToBounds=YES;
        headImage.layer.cornerRadius=37.5;
        WS(weakSelf);
        [headImage sd_setImageWithURL:[NSURL URLWithString:model.Avater] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                CIContext *context = [CIContext contextWithOptions:nil];
                CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
                CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
                [filter setValue:ciImage forKey:kCIInputImageKey];
                //设置模糊程度
                [filter setValue:@30.0f forKey: @"inputRadius"];
                CIImage *result = [filter valueForKey:kCIOutputImageKey];
                CGImageRef outImage = [context createCGImage: result fromRect:ciImage.extent];
                UIImage * blurImage = [UIImage imageWithCGImage:outImage];
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.topImageV.image=blurImage;
                });
            });
        }];
        [_topImageV addSubview:headImage];
        [headImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_topImageV);
            make.top.equalTo(_topImageV).with.offset(real_size(25+iphoneX));
            make.size.mas_equalTo(CGSizeMake(75, 75));
        }];

        QXLable *labName=[[QXLable alloc]init];
        labName.font=[UIFont boldSystemFontOfSize:15];
        labName.textAlignment=NSTextAlignmentRight;
        labName.text=model.NickName;
        labName.textColor=[UIColor whiteColor];
        CGFloat width=[TGTools boundingRectWithString:labName.text withWidth:SCREEN_WIDTH anfont:labName.font];
        [_topImageV addSubview:labName];
        [labName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headImage.mas_bottom).with.offset(5);
            make.centerX.equalTo(headImage).with.offset(-(width/2.0));
            make.size.mas_equalTo(CGSizeMake(width+10, 30));
        }];

        UIImageView *sexImage=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"man"]];
        if (model.Sex) {
            sexImage.image=[UIImage imageNamed:@"woman"];
        }
        [_topImageV addSubview:sexImage];
        [sexImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(labName);
            make.left.equalTo(labName.mas_right).with.offset(10);
            make.size.mas_equalTo(sexImage.image.size);
        }];

        if (![self.userId isEqualToString:[UserModel userModel].UserId]) {
            [[MyVM manage] getHasFollowWithId:self.userId andSuccess:^(id returnValue) {
                
                model.isFollow=[[returnValue objectForKey:@"Followed"] boolValue];
                UIButton *btnFocus =[[UIButton alloc]init];
                [btnFocus setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                btnFocus.layer.masksToBounds=YES;
                btnFocus.layer.borderWidth=1.0;
                btnFocus.layer.cornerRadius=2.0;
                [btnFocus addTarget:weakSelf action:@selector(onclickFocus:) forControlEvents:UIControlEventTouchUpInside];
                if (model.isFollow) {
                    [btnFocus setTitle:@"已关注" forState:UIControlStateNormal];
                    
                }else{
                    [btnFocus setTitle:@"关注" forState:UIControlStateNormal];
                }
                [btnFocus.titleLabel setFont:[UIFont systemFontOfSize:10]];
                btnFocus.layer.borderColor=[UIColor whiteColor].CGColor;
                [_topImageV addSubview:btnFocus];
                [btnFocus mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(sexImage);
                    make.left.equalTo(sexImage.mas_right).with.offset(10);
                    make.size.mas_equalTo(CGSizeMake(35, 20));
                }];
            } andFail:^(NSString *errorMessage, NSError *error) {
                
            }];
            
            
        }else{
            [labName mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(headImage).with.offset(-10);
            }];
        }
        
        
        QXLable *labSign=[[QXLable alloc]init];
        labSign.font=[UIFont systemFontOfSize:10];
        labSign.textColor=[UIColor whiteColor];
        labSign.textAlignment=NSTextAlignmentCenter;
        labSign.text=model.Autograph.length>0?model.Autograph:@"这个人很懒...";
        [_topImageV addSubview:labSign];
        [labSign mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_topImageV);
            make.top.equalTo(labName.mas_bottom);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-80, 50));
        }];
    }
    return _topImageV;
}

- (void)headView{
    float iphoneX=0;
    if (KIsiPhoneX) {
        iphoneX=20;
    }
    headView=[[UIView alloc]init];
    headView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@(real_size(178+50+iphoneX)));
    }];
    
    [headView addSubview:self.topImageV];
    QXLable *labFocus=[self viewWithTitle:@"关注" andValue:model.Follow];
    labFocus.tag=0;
    [headView addSubview:labFocus];
    [labFocus mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(headView);
        make.left.equalTo(headView);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, real_size(50)));
    }];

    QXLable *labFans=[self viewWithTitle:@"粉丝" andValue:model.Fans];
    labFans.tag=2    ;
    [headView addSubview:labFans];
    [labFans mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(headView);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, real_size(50)));
    }];
}

- (QXLable *)viewWithTitle:(NSString *)title andValue:(NSString *)value {
    QXLable *labTitle=[[QXLable alloc]initWithFount:13];
    labTitle.numberOfLines=0;
    labTitle.userInteractionEnabled=YES;
    labTitle.textAlignment=NSTextAlignmentCenter;
    NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n%@",value,title]];
    [attStr addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTBLACKCOLOR range:NSMakeRange(0, value.length)];
    [attStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(0, value.length)];
    labTitle.attributedText=attStr;
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [labTitle addGestureRecognizer:tap];
    return labTitle;
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (NSMutableArray *)getFArr{
    if (!_getFArr) {
        _getFArr=[[NSMutableArray alloc]init];
    }
    return _getFArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
